package mainService.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import mainService.HTTPService;
import mainService.ServiceParams;
import mainService.data.HttpMessageWriter;
import mainService.data.MimeHTTP;

/**
 * Un generico File Server, gestisce file html, file css e file js
 * 
 * @author Daniel Procop, Mattia Grecchi
 */
public class HttpFileServer implements HTTPService {

	@Override
	public ArrayList<String> getServiceResult(ServiceParams params) {

		String filename = params.getValue("file");

		if (filename == null) {
			filename = "web_interface/errore.html";
		}

		MimeHTTP mime = MimeHTTP.getMimeByFilename(filename);

		File file;
		if (filename.endsWith("xml")) {
			file = new File("menus/" + filename);
		} else {
			file = new File("web_interface/" + filename);
		}

		if (!file.exists() || file.isDirectory()) {
			file = new File("web_interface/errore.html");
		}

		HttpMessageWriter writer = new HttpMessageWriter(mime);
		ArrayList<String> risposta = writer.createHttpMessageHeader();

		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line = reader.readLine();
			while (line != null) {
				risposta.add(line);
				line = reader.readLine();
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return risposta;
	}
}
